package com.jinhuhang.u2.invertmodule;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.ExperienceGoldEntity;
import com.jinhuhang.u2.entity.ExperienceMoneyEntity;
import com.jinhuhang.u2.invertmodule.adapter.ExperienceAdapter;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.badge.MathUtil;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.util.MathUtils;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.MyResult;
import com.jinhuhang.u2.util.http.MyResultList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by caoxiaowei on 2017/9/11.
 */
public class ConfirmExperienceActivity extends SimpleBaseActivity {
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.income)
    TextView mIncome;
    @Bind(R.id.moneyexpe)
    TextView mMoneyexpe;
    @Bind(R.id.jiantou)
    ImageView mJiantou;
    //    @Bind(R.id.radioButton)
//    RadioButton mRadioButton;
//    @Bind(R.id.radioButton2)
//    RadioButton mRadioButton2;
//    @Bind(R.id.radiogroup)
//    RadioGroup mRadiogroup;
//    @Bind(R.id.comfirm)
//    TextView mComfirm;
    ExperienceAdapter mExperienceAdapter;
    boolean show = false;
    @Bind(R.id.experiencelist)
    ListView mExperiencelist;
    @Bind(R.id.laylist)
    LinearLayout mLaylist;

    List<ExperienceGoldEntity> mExperienceGoldEntities = new ArrayList<>();
    @Bind(R.id.surpluse_ex)
    TextView mSurpluseEx;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_confirmexceprience;
    }

    int bid;
    String id = "0";
    private int term;
    private String apr,title;
    @Override
    protected void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        if (MainActivity.userbean != null) {
            id = MainActivity.userbean.getUserId();
            mSurpluseEx.setText(MainActivity.userbean.getUseMoney()+"");
        }
        getMoneyList();
        bid = getIntent().getIntExtra("bid", 0);
        double virtualMoney  = getIntent().getDoubleExtra("virtualMoney",0);
        term= getIntent().getIntExtra("term", 0);
        apr =  getIntent().getStringExtra("apr");
        title  = getIntent().getStringExtra("title");
        mTvTitle.setText(getResources().getString(R.string.tijian));
        mSurpluseEx.setText(virtualMoney+"元");
        mMoneyexpe.setText(virtualMoney+"元");
        money= virtualMoney;
        BigDecimal  targetBigDecimal =  new BigDecimal(String.valueOf(virtualMoney));
        BigDecimal result = (targetBigDecimal.multiply((new BigDecimal(apr).divide(new BigDecimal(100),4, RoundingMode.DOWN)))).divide(new BigDecimal(365),4,RoundingMode.DOWN).multiply(new BigDecimal(term));
        BigDecimal caculateResult =result.setScale(2,   BigDecimal.ROUND_HALF_UP);
        mIncome.setText(caculateResult.toString()+"元");
        mExperienceAdapter = new ExperienceAdapter(mExperienceGoldEntities, this);
        mExperiencelist.setAdapter(mExperienceAdapter);
        mExperiencelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            }
        });
    }

    List<String> list = new ArrayList<>();
    double money=0;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageTag event) {/* Do something */
        if (event.add) {
            list.add(event.postion);
        } else {
            list.remove(event.postion);
        }
        money=0;
        for (String ea:list){
            money =MathUtils.add(String.valueOf(money),mExperienceGoldEntities.get(Integer.parseInt(ea)).getMoney());
        }
        if(money<=0){
            mIncome.setText("0元");
            mMoneyexpe.setText("0元");

        }else{
            mMoneyexpe.setText(money+"元");
            BigDecimal  targetBigDecimal =  new BigDecimal(String.valueOf(money));
            BigDecimal result = (targetBigDecimal.multiply((new BigDecimal(apr).divide(new BigDecimal(100),4, RoundingMode.DOWN)))).divide(new BigDecimal(365),4,RoundingMode.DOWN).multiply(new BigDecimal(term));
            BigDecimal caculateResult =result.setScale(2,   BigDecimal.ROUND_HALF_UP);
            mIncome.setText(caculateResult.toString()+"元");
        }
  //      MyLogger.i(list.toString());
    }

    @OnClick({R.id.experiencelay, R.id.back, R.id.comfirm})
    void onclick(View view) {
        switch (view.getId()) {
            case R.id.experiencelay:
                if (show) {
                    show = false;
                    mJiantou.setImageResource(R.drawable.touzi_tiaozhuan);
                    mExperiencelist.setVisibility(View.GONE);
                    mLaylist.setVisibility(View.GONE);
                } else {
                    show = true;
                    mJiantou.setImageResource(R.drawable.touzi_downbutton_layout);
                    mExperiencelist.setVisibility(View.VISIBLE);
                    mLaylist.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.back:
                finish();
                break;
            case R.id.comfirm:
                checkToken();
                break;
        }
    }

    private void checkToken(){
        addSubscription(RetrofitUtils.getInstance().build()
                .checkToken(MainActivity.userbean.getUserId(),MainActivity.userbean.getToken())
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> o) {
                        if (o.getCode()==200){
                            invert();
                            MainActivity.checktoken=true;
                        }else {
                            //token 失效
                            MainActivity.checktoken=false;
                            MainActivity.tip=null;
                            if (o.getCode()!=301) {
                                MainActivity.tip=o.getInfo();
                            }
                            if (MainActivity.tip!=null) {
                                CustomToast.showToast(MainActivity.tip);
                            }
                            Intent intent=new Intent(MyApplication.getContext(), UserActivity.class);
                            intent.putExtra("type",UserActivity.LOGIN);
                            startActivity(intent);
                            finish();
                        }
                    }

                }));
    }
    private void getMoneyList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", "1");
        map.put("type", "0");
        map.put("pageSize", "50");
        map.put("userId", id);
        addSubscription(RetrofitUtils.getInstance().build()
                .experienceGold(map)
                .compose(T.defaultScheduler())
                .subscribe(new MyResultList<MyResult<ExperienceGoldEntity>>() {
                    @Override
                    protected void onSuccess(MyResult<ExperienceGoldEntity> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            mExperienceGoldEntities.addAll(data.getData());
                            for (int i=0;i<data.getData().size();i++){
                                list.add(i+"");
                            }
                            mExperienceAdapter.notifyDataSetChanged();
                        }
                    }
                }));
    }

    double sum = 0;
    private void invert() {
        String captialIds = "";

        if (list.size() == 0) {
            MyDialog.experienceGold(this);
            return;
        }
        for (String str : list
                ) {
            int p = Integer.parseInt(str);
            captialIds =captialIds + mExperienceGoldEntities.get(p).getId() + "-";
            sum = MathUtils.add(String.valueOf(sum),mExperienceGoldEntities.get(p).getMoney());
        }
        captialIds=captialIds.substring(0,captialIds.length()-1);

//        if (money<=0){
//            CustomToast.showToast("请选择体验金！");
//            return;
//        }
        Map<String, String> map = new HashMap<>();
        map.put("captialIds", captialIds);
        map.put("virtualId", String.valueOf(bid));
        map.put("amount", String.valueOf(sum));
        map.put("userId", id);
        map.put("source", "3");//安卓
        addSubscription(RetrofitUtils.getInstance().build()
                .experienceInvert(map)
                .compose(T.defaultScheduler())
                .subscribe(new MyResultList<MyResult<ExperienceMoneyEntity>>() {

                    @Override
                    protected void onSuccess(MyResult<ExperienceMoneyEntity> data) {
                        Intent intent = new Intent(ConfirmExperienceActivity.this, ResultActivity.class);
                        if (data.code == Constant.SUCCESS_CODE) {
                            intent.putExtra("title", title);
                            intent.putExtra("apr", apr);
                            intent.putExtra("term", term+"天");
                            intent.putExtra("money", sum+"");
                            intent.putExtra("type", Constant.experience_success);
                            startActivity(intent);
                        } else {
                            intent.putExtra("type", Constant.experience_fail);
                            startActivity(intent);
                        }
                    }
                }));
    }

    @Override
    protected void ondestory() {
        super.ondestory();
        EventBus.getDefault().unregister(this);
    }
}
